package diona.model

import org.squeryl.annotations._
import net.liftweb.record.field.{StringField, LongField}
import net.liftweb.squerylrecord.KeyedRecord
import net.liftweb.record.{MetaRecord, Record}
import net.liftweb.squerylrecord.RecordTypeMode._

/**
 * User: anton
 * Date: 27.03.11 13:43
 */
class GoogleAuth extends Record[GoogleAuth] with KeyedRecord[Long] {
  override def meta = GoogleAuth

  @Column(name = "id")
  override val idField = new LongField(this)

  val authToken = new StringField(this, "")
  val userId = new LongField(this)
}

object GoogleAuth extends GoogleAuth with MetaRecord[GoogleAuth]  {
  def save(authToken: String, user: User): GoogleAuth =
  {
    val authInfo = GoogleAuth.createRecord.authToken(authToken).userId(user.id.value)
    inTransaction { PublisherSchema.googleAuths.insert(authInfo) }
    authInfo
  }

  def update(authToken: String, user: User): GoogleAuth =
  {
    inTransaction {
      val authInfo: GoogleAuth = byUser(user).get
      authInfo.authToken(authToken)
      PublisherSchema.googleAuths.update(authInfo)
      authInfo
    }
  }

  def byUser(user: User): Option[GoogleAuth] =
  {
    inTransaction {
      PublisherSchema.googleAuths.where(a => a.userId === user.id).headOption
    }
  }
}